import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/config.dart';

class CartypeSelectRoute extends StatefulWidget {
  final Map param;
  final String bid;
  final String tid;
  CartypeSelectRoute(this.param, this.bid, this.tid);
  @override
  State<StatefulWidget> createState() {
    return new _BrandSelectRouteState(this.param, this.bid, this.tid);
  }
}

class _BrandSelectRouteState extends State<CartypeSelectRoute> {
  // List<CityInfo> _cityList = List();
  // List<CityInfo> _hotCityList = List();
  final Map param;
  final String bid;
  final String tid;
  _BrandSelectRouteState(this.param, this.bid, this.tid);
  List BrandList = List();
  List hotList = List();
  List<double> heights = List();
  ScrollController scrollController = new ScrollController();
  TextEditingController texts = new TextEditingController();

  int _suspensionHeight = 40;
  int _itemHeight = 50;
  String _suspensionTag = "";

  String name = "";

  @override
  void initState() {
    super.initState();
    scrollController.addListener(() {
      double position = scrollController.offset.toDouble();
      // int index = _computerIndex(position);
      // setState(() {
      //  // defaultIndex = index;
      // });
    });
    loadData();
  }
  // int _computerIndex(double position) {
  //   if (widget.data != null) {
  //     for (int i = 0; i < widget.data.length - 1; i++) {
  //       double pre = _computerIndexPosition(i);
  //       double next = _computerIndexPosition(i + 1);
  //       if (position > pre && position < next) {
  //         return i;
  //       }
  //     }
  //   }
  //   return 0;
  // }

  // double _computerIndexPosition(int index) {
  //   int n = 0;
  //   if (widget.data != null) {
  //     for (int i = 0; i < index; i++) {
  //       n += (widget.data[i]['userList'].length).toInt();
  //     }
  //   }
  //   return n * widget.itemHeight + (index + 1) * widget.suspensionHeight;
  // }
  void loadData() async {
    Map<String, String> map = new Map();
    map["bid"] = this.bid;
    String url = HttpHelper.API_CarType;
    if (this.tid != '0') {
      url = HttpHelper.API_Car_typeList;
      map['id'] = this.tid;
    }
    HttpHelper.post(url, (data) async {
      //loadpage.close();
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          List temp = data["info"];
          setState(() {
            BrandList = temp;
          });
          //           print('1111');
          // List temp = data["info"];

        }
      }
    }, params: map);
  }

  Widget layout() {
    List<Widget> tiles = [];
    Widget content;
    if (this.tid != '0') {
      tiles.add(
        Padding(
          padding: new EdgeInsets.fromLTRB(10, 0, 0, 10),
          child: new TextField(
            decoration: new InputDecoration(
              // border: InputBorder.none,
              hintText: '若无款式，请输入',
            ),
            onChanged: (value) {
              setState(() {
                name = value;
              });
            },
            controller: texts,
            onSubmitted: (va) {
              print(va);
              param["value"] = va;
              param["typelist_id"] = '0';
              Navigator.pop(context);
            },
          ),
        ),
      );
      var btn = new Container(
          color: Color.fromRGBO(255, 255, 255, 1),
          //color:Colors.white,
          child: new Padding(
              padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
              child: new Material(
                color: Color.fromRGBO(255, 255, 255, 1),
                //INK可以实现装饰容器
                child: new Ink(
                  //用ink圆角矩形
                  //color: Color.fromRGBO(239, 239, 239, 1),
                  decoration: new BoxDecoration(
                    //背景

                    color: Color.fromRGBO(255, 204, 48, 1),
                    //设置四周圆角 角度
                    borderRadius: BorderRadius.all(Radius.circular(18.0)),
                    //设置四周边框
                    border: new Border.all(
                        width: 1, color: Color.fromRGBO(255, 204, 48, 1)),
                  ),
                  child: new InkWell(

                      //圆角设置,给水波纹也设置同样的圆角
                      //如果这里不设置就会出现矩形的水波纹效果
                      borderRadius: new BorderRadius.circular(15.0),
                      //设置点击事件回调
                      onTap: () {
                        param["value"] = name;
                        param["typelist_id"] = '0';
                        Navigator.pop(context);
                      },
                      child: Container(
                        //设置 child 居中
                        alignment: Alignment(0, 0),
                        height: 36,
                        //color: Color.fromRGBO(239, 239, 239, 1),
                        width: double.infinity,
                        child: Text(
                          "确认",
                          style: TextStyle(color: Colors.white),
                        ),
                      )),
                ),
              )));
      tiles.add(btn);
    }
    for (var item in BrandList) {
      tiles.add(GestureDetector(
        onTap: () {
          param["value"] = item["name"];
          if (this.tid != '0') {
            param["typelist_id"] = item["id"];
            param["price"] = item["price"];
          } else {
            param["type_id"] = item["id"];
          }
          Navigator.of(context).pop(param);
          // Navigator.pop(context);
        },
        child: new Container(
            //color: Colors.red,
            height: 50,
            width: double.infinity,
            decoration: new BoxDecoration(
              border: new Border(
                  bottom: BorderSide(width: 1, color: Color(0xffe5e5e5))),

              // borderRadius: new BorderRadius.all(new Radius.circular(20.0)),
            ),
            child: new Padding(
                padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
                child: new Row(children: <Widget>[
                  tid == "0"
                      ? item['pic_url'] == ""
                          ? Image.asset(
                              'resource/images/jiance/carmodel1.jpeg',
                              width: 100,
                              height: 40,
                            )
                          : Image.network(item['pic_url'],
                              width: 100, height: 40)
                      : new Container(height: 0),
                  Padding(
                      padding: new EdgeInsets.fromLTRB(5, 0, 10, 0),
                      child: Text(item["name"]))
                  //Image.network(item["pic_url"],width: 100,height: 30,)
                ]))),
      ));
    }

    content = new Padding(
        padding: new EdgeInsets.fromLTRB(10, 0, 10, 10),
        child: new Column(
            children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
            //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
            ));
    return content;
  }

  Widget buildcontent(item) {
    List<Widget> tiles = [];
    Widget content;
    var list = item["userList"];
    for (var items in list) {
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
          child: Container(
              width: double.infinity - 50,
              height: 50,
              child: GestureDetector(
                  onTap: () {
                    param["value"] = items["name"];
                    param["brand_id"] = items["id"];
                    Navigator.pop(context);
                  },
                  child: new Row(children: <Widget>[
                    items['pic_url'] == ""
                        ? Image.asset(
                            'resource/images/jiance/carmodel1.jpeg',
                            width: 100,
                            height: 50,
                          )
                        : Image.network(items['pic_url'],
                            width: 100, height: 50),
                    // Image.asset(
                    //   'resource/images/jiance/carmodel1.jpeg',
                    //   width: 100,
                    //   height: 50,
                    // ),
                    Padding(
                        padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                        child: Text(items["name"]))
                    //Image.network(item["pic_url"],width: 100,height: 30,)
                  ])))));
    }
    content = new Padding(
        padding: new EdgeInsets.fromLTRB(0, 20, 0, 20),
        child: new Column(
            children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
            //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
            ));
    return content;
  }

  Widget indexbar() {
    List<Widget> tiles = [];
    Widget content;
    // var list = item["userList"];
    for (var i = 0; i < BrandList.length; i++) {
      var item = BrandList[i];
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
          child: GestureDetector(
              onTap: () {
                print('点击索引' + i.toString());
                double y = 0.0;
                for (var j = 0; j < heights.length; j++) {
                  // print(he)
                  if (j < i) y += heights[j];
                }
                print(y.toString());
                scrollController.animateTo(y,
                    duration: new Duration(seconds: 1), curve: Curves.ease);
              },
              child: Container(
                  width: double.infinity - 50,
                  height: 20,
                  child: Text(item["tag"])))));
    }
    content = new Padding(
        padding: new EdgeInsets.fromLTRB(0, 20, 0, 20),
        child: new Column(
            children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
            //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
            ));
    return content;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          titleSpacing: 0,
          title: new Text('车型',style: TextStyle(fontSize: Config.title_size),),
          backgroundColor: Colors.white,
          elevation: 0,
          // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
        ),
        body: new Center(
            child: Container(
                decoration: new BoxDecoration(
                    //color: Color.fromRGBO(238, 238, 238, 1),
                    ),
                child: Padding(
                    padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
                    child: Stack(
                      children: <Widget>[
                        Align(
                          alignment: Alignment.centerLeft,
                          child: new ListView(
                              controller: scrollController,
                              children: <Widget>[layout()]),
                        ),
                        // Align(

                        //     alignment: Alignment.topRight,

                        //     child: new Container(
                        //       width:30,
                        //       child:
                        //     indexbar(),
                        //     ))
                      ],
                    )
                    // new ListView(
                    //   children: <Widget>[buildcontent()],
                    // )),
                    ))));
  }
}

class Suspension extends StatelessWidget {
  final String tag;
  final double suspensionHeight;

  Suspension({this.tag, this.suspensionHeight});

  @override
  Widget build(BuildContext context) {
    return Offstage(
      child: new Container(
        child: new Text(
          "$tag",
        ),
        alignment: Alignment.centerLeft,
        margin: const EdgeInsets.only(left: 16.0),
        height: suspensionHeight,
      ),
      offstage: false,
    );
  }
}
